extends Node2D

class_name Board

@export var board_size: Vector2 = Vector2(2050, 3970)  # 棋盘尺寸
@export var board_position: Vector2 = Vector2(80, 198)  # 棋盘位置
@export var board_scale: Vector2 = Vector2(0.25, 0.25)  # 棋盘缩放
@export var block_scene: PackedScene  # 方块场景
@export var background_texture: Texture2D  # 背景纹理 (Border.png)
@export var fall_interval: float = 1.0  # 自动下落间隔(秒)

signal score_updated(score)
signal game_over
var current_block: Node2D
var score: int = 0
var board_rect: Rect2  # 棋盘实际边界(考虑缩放)
var fall_timer: Timer = Timer.new()
var block_textures: Array = []  # 存储所有方块纹理

func _ready():
	# 初始化棋盘属性
	position = board_position
	scale = board_scale
	
	# 设置背景
	var background = Sprite2D.new()
	background.texture = background_texture
	background.scale = board_size / background.texture.get_size()
	background.centered = false
	add_child(background)
	background.z_index = -1
	
	# 计算实际边界(像素)
	board_rect = Rect2(Vector2.ZERO, board_size)
	
	# 加载方块纹理
	load_block_textures()
	
	# 初始化下落计时器
	fall_timer.wait_time = fall_interval
	fall_timer.autostart = false
	fall_timer.timeout.connect(_on_fall_timeout)
	add_child(fall_timer)

func load_block_textures():
	# 加载Assets文件夹中的所有颜色方块纹理
	var dir = DirAccess.open("res://Assets/")
	if dir != null:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "":
			if file_name.ends_with(".png") and !file_name.begins_with("Border"):
				var texture = load("res://Assets/" + file_name)
				if texture:
					block_textures.append(texture)
			file_name = dir.get_next()
		dir.list_dir_end()
	else:
		push_error("无法打开Assets文件夹")
	if block_textures.is_empty():
		push_error("未找到方块纹理，请检查Assets文件夹")

func start_new_game():
	# 清除现有方块
	for child in get_children():
		if child.has_method("is_block"):
			child.queue_free()
	score = 0
	score_updated.emit(score)
	spawn_new_block()

func spawn_new_block():
	if block_textures.is_empty():
		return
	
	# 随机选择纹理
	var random_texture = block_textures[randi() % block_textures.size()]
	
	# 检查方块场景是否已设置
	if block_scene == null:
		push_error("方块场景未设置，请在编辑器中为Board节点的block_scene属性赋值")
		return
	
	# 实例化方块
	current_block = block_scene.instantiate()
	current_block.position = Vector2(
		randf_range(board_rect.position.x + current_block.size.x/2, board_rect.end.x - current_block.size.x/2),
		board_rect.position.y + current_block.size.y/2
	)
	current_block.set_texture(random_texture)
	add_child(current_block)
	
	# 连接方块信号
	current_block.connect("position_changed", self._on_block_position_changed)
	current_block.connect("landed", self._on_block_landed)
	current_block.connect("drag_started", self._on_drag_started)
	current_block.connect("drag_ended", self._on_drag_ended)

func _on_block_position_changed(new_position):
	# 限制方块在棋盘内
	var block_size = current_block.size
	current_block.position = new_position.clamp(
		Vector2(board_rect.position.x + block_size.x/2, board_rect.position.y + block_size.y/2),
		Vector2(board_rect.end.x - block_size.x/2, board_rect.end.y - block_size.y/2)
	)

func _on_block_landed():
	# 检查是否触底
	var block_bottom = current_block.position.y + current_block.size.y/2
	if block_bottom >= board_rect.end.y - 1:
		score += 10
		score_updated.emit(score)
		# 检查游戏结束(顶部溢出)
		if current_block.position.y - current_block.size.y/2 <= board_rect.position.y:
			game_over.emit()
			return
		spawn_new_block()
	else:
		fall_timer.start()

func _on_fall_timeout():
	# 自动下落一个方块高度
	current_block.position += Vector2(0, current_block.size.y)
	_on_block_position_changed(current_block.position)
	_on_block_landed()

func _on_drag_started():
	fall_timer.stop()

func _on_drag_ended():
	_on_block_landed()
